package com.cgnpc.scp.hr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.bean.CreateFileInfo;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.service.AppConstantService;
import com.cgnpc.scp.common.utils.BpmUtil;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.hr.mybatis.entity.HrUserInfo;
import com.cgnpc.scp.hr.mybatis.mapper.client.HrUserInfoMapper;
import com.cgnpc.scp.hr.service.HrUserInfoService;
import com.cgnpc.scp.run.utils.CommonExportUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service("userInfoService")
public class HrUserInfoServiceImpl implements HrUserInfoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HrUserInfoServiceImpl.class);

    @Autowired
    private HrUserInfoMapper hrUserInfoMapper;

    @Autowired
    private CurrentUser currentUser;

    @Autowired
    private AppConstantService appConstantService;

    @Autowired
    private SqlSession sqlSession;

    @Override
    public MyPageResult<HrUserInfo> queryListPage(Map<String, Object> params) {
        MyPageResult<HrUserInfo> re = null;
        int pageNum = 1;
        int pageSize = 10;
        try {
            pageNum = Integer.parseInt(params.get("pageNum") + "");
            pageSize = Integer.parseInt(params.get("pageSize") + "");
        }catch (Exception e){
            e.printStackTrace();
        }
        Page<HrUserInfo> queryPage = PageHelper.startPage(pageNum, pageSize);
        hrUserInfoMapper.listPage(params);
        PageInfo<HrUserInfo> pageResult = new PageInfo<>(queryPage.getResult());
        re = MyPageResultUtil.createMyPageResult(pageResult);

        return re;
    }

    @Override
    public AjaxResult info(String id) {
        return AjaxResult.success().put("data", hrUserInfoMapper.selectById(id));
    }

    @Override
    public AjaxResult delete(List<String> ids) {
        if(ids == null || ids.size() == 0){
            return AjaxResult.success();
        }
        for(String id : ids){
            hrUserInfoMapper.deleteById(id);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult save(HrUserInfo hrUserInfo) {
        List<HrUserInfo> hrUserInfos = hrUserInfoMapper.selectList(new QueryWrapper<HrUserInfo>()
        .eq("user_no",hrUserInfo.getUserNo()));
        if(hrUserInfos != null && hrUserInfos.size() != 0){
            return AjaxResult.error("userNo is already exists");
        }

        hrUserInfo.setId(IDHelper.uuid());
        Date date = new Date();
        hrUserInfo.setCreateTime(date);
        hrUserInfo.setCreateUser(currentUser.getCurrentUserDetail().getUserId());
        hrUserInfo.setCreateUserName(currentUser.getCurrentUserDetail().getUserName());

        hrUserInfo.setLastUpdateTime(date);
        hrUserInfo.setLastUpdateUser(currentUser.getCurrentUserDetail().getUserId());
        hrUserInfo.setLastUpdateUserName(currentUser.getCurrentUserDetail().getUserName());

        hrUserInfoMapper.insert(hrUserInfo);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult update(HrUserInfo hrUserInfo) {
        Date date = new Date();
        hrUserInfo.setLastUpdateTime(date);
        hrUserInfo.setLastUpdateUser(currentUser.getCurrentUserDetail().getUserId());
        hrUserInfo.setLastUpdateUserName(currentUser.getCurrentUserDetail().getUserName());

        hrUserInfoMapper.updateById(hrUserInfo);
        return AjaxResult.success();
    }

    @Override
    public Boolean importFromExcel(MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        List<HrUserInfo> hrUserInfos = new ArrayList<>();
        try{
            Workbook workbook = WorkbookFactory.create(is);
            handleExcel(hrUserInfos,workbook);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            is.close();
        }
        hrUserInfos.forEach( info -> {
            hrUserInfoMapper.insert(info);
        });
        return true;
    }

    /**********************************
     * 用途说明: 处理excel
     * 参数说明 file
     * 返回值说明:
     ***********************************/
    void handleExcel(List<HrUserInfo> hrInfoList, Workbook workbook) throws Exception{
        if(workbook == null){
            throw new Exception("Excel工作簿为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            sheet = workbook.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            int sheetNum = sheet.getLastRowNum();
            if(sheetNum < 8){
                throw new Exception("导入数据为空");
            }
            //遍历当前sheet中的所有行
            for (int j = 8; j <= sheetNum ; j++) {
                row = sheet.getRow(j);
                if (row == null ) {
                    continue;
                }
                HrUserInfo info = new HrUserInfo();
                List<Map<String, String>> fieldNameList = new ArrayList<>();
                Map<String, String> indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "userNo");indexFieldNameMap.put("fieldName", "员工号");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "name");indexFieldNameMap.put("fieldName", "姓名");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "sex");indexFieldNameMap.put("fieldName", "性别");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "backendDepartment");indexFieldNameMap.put("fieldName", "后台所属模块/分部/所");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "backendNo");indexFieldNameMap.put("fieldName", "后台岗位编号");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "backendName");indexFieldNameMap.put("fieldName", "后台岗位名称");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "frontendProject");indexFieldNameMap.put("fieldName", "前台所属项目部");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "frontendDepartment");indexFieldNameMap.put("fieldName", "前台所属分部");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "frontendQueue");indexFieldNameMap.put("fieldName", "前台所属队");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "frontendNo");indexFieldNameMap.put("fieldName", "前台岗位编号");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "frontendName");indexFieldNameMap.put("fieldName", "前台岗位名称");
                fieldNameList.add(indexFieldNameMap);indexFieldNameMap = new HashMap<>();
                indexFieldNameMap.put("field", "workAddress");indexFieldNameMap.put("fieldName", "现工作地");
                fieldNameList.add(indexFieldNameMap);
                //1代表必填，0代表可为空
                List<Integer> requireFile = Arrays.asList(1,1,1,1,1,1,0,0,0,0,0,1);

                //把每个单元格的值付给对象的对应属性
                Map<String, Object> data = new HashMap<>();
                for(int x=0; x<requireFile.size(); x++){
                    Map<String, String> fieldData = fieldNameList.get(x);
                    if(row.getCell(x) != null){
                        data.put(fieldData.get("field"), row.getCell(x).toString());
                    }else{
                        if(1 == requireFile.get(x)){
                            throw new Exception("导入的第"+(j + 1)+"行中"+fieldData.get("fieldName")+"不存在");
                        }

                    }
                }
                BpmUtil.mapToObject(data, info);
                info.setId(IDHelper.uuid());
                info.setCreateTime(new Date());
                hrInfoList.add(info);
            }
        }
    }

    @Override
    public CreateFileInfo exportExcel(Map<String, Object> params) throws Exception {
        final String logInfo = "[exportExcel_UUID_" + UUID.randomUUID() + "]";
        CreateFileInfo createFileInfo = null;

        try {
            List<String> titleList = Arrays.asList(
                    "员工号","姓名","性别","后台所属模块/分部/所","后台岗位编号","后台岗位名称"
                    ,"前台所属项目部","前台所属分部","前台所属队","前台岗位编号","前台岗位名称","现工作地"
            );
            List<String> fields = Arrays.asList(
                    "userNo","name","sex","backendDepartment","backendNo","backendName"
                    ,"frontendProject","frontendDepartment","frontendQueue"
                    ,"frontendNo","frontendName","workAddress"
            );

            CommonExportUtil<HrUserInfo> util = new CommonExportUtil<>();
            createFileInfo = util.exportExcel(appConstantService, sqlSession, titleList, fields
                    , "com.cgnpc.scp.hr.mybatis.mapper.client.HrUserInfoMapper"
                    ,"listPageExport", params);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return createFileInfo;
    }
}
